import navigationComponent from './component';

class Navigation {
    keyName = null
    // 曾经来过
    haveBeenTo = !!sessionStorage.haveBeenTo
    to = null
    from = null
    history = sessionStorage.history ? sessionStorage.history.split('|') : new Array()
    currentRouteId = null
    direction = null
    beforeEachList = new Array()

    constructor({router, keyName = 'vnk'}) {
        this.keyName = keyName;
        navigationComponent(this);
        router.beforeEach((to, from, next) => {
            const key = to.query[keyName];
            if (!key) {
                next({...to, query: {...to.query, [keyName]: this._getKey()}, replace: !this.haveBeenTo});
            } else {
                this.to = to;
                this.from = from;
                this._getCurrentRouteId();
                this._getDirection(to, from);
                this._saveHistory();
                this._runbeforeEach(next);
            }
            this.haveBeenTo = sessionStorage.haveBeenTo = true;
        });
    }

    _getKey() {
        return Date.now();
    }


    _getCurrentRouteId() {
        const {keyName} = this;
        const {name, path} = this.to;
        const key = this.to.query[keyName];
        let id = path;
        if (name) {
            id = name;
        }
        this.currentRouteId = id + ',' + key;
    }

    _getDirection(to, from) {
        const {history, currentRouteId} = this;
        const index = history.indexOf(currentRouteId);
        if (index == -1) {// 前进
            history.push(currentRouteId);
            this._onForward();
            const forward = to.matched[0].components.default;
            if (!from.matched.length) return;
            const parent = from.matched[0].instances.default;
            console.log(forward);
            forward.mixins = [{
                data() {
                    this.$prev = parent;
                }
            }];
        } else if (index != history.length - 1) { // 后退
            history.pop();
            this._onBack();
        } else {
            // 刷新
            this._onRefresh();
        }
    }

    _saveHistory() {
        sessionStorage.history = this.history.join('|');
    }

    _onForward() {
        this.direction = 'forward';
    }

    _onBack() {
        this.direction = 'back';
    }

    _onRefresh() {
        this.direction = 'refresh';
    }

    async _runbeforeEach(next) {
        const {to, from, direction, beforeEachList} = this;

        for (let fun of beforeEachList) {
            await new Promise(resolve => fun(to, from, x => x == false ? next(false) : resolve(), direction));
        }
        next(true);
    }

    beforeEach(fun) {
        this.beforeEachList.push(fun);
    }

    cleanHistory() {
        this.history = new Array();
        sessionStorage.history = '';
    }

    // static install(Vue, { navigation }) {
    //
    // }
}

export default Navigation;